//
//  AdoptTribalSelectedViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/9/4.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "AdoptTribalSelectedViewController.h"
#import "AdoptTribalSelectedCell.h"
#import "MeatOrderBox.h"
#import "TribalSelectedBox.h"
#import "VarietyListViewController.h"

@interface AdoptTribalSelectedViewController ()

@property (nonatomic, strong) UIView *topTipsBgView;
@property (nonatomic, strong) YYLabel *topTipsLab;
@property (nonatomic, strong) UILabel *selecttribeTitleLab;
@property (nonatomic, strong) UIButton *confirmBtn;
@property (nonatomic, strong) UILabel *tipLab;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSMutableArray *values;

@property (nonatomic, strong) SelectTribesList *model;
@property (nonatomic, strong) RangeSelectModel *selectModel;
@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) NSNumber *selectTribeId;

@end

@implementation AdoptTribalSelectedViewController


- (void)setupUI {
    
    {
        self.baseNavView.navTitleLabel.text = @"选择部落";
        self.baseNavView.line.hidden = YES;
        self.view.backgroundColor = [UIColor whiteColor];
    }
    
    {
        [self.view addSubview:self.topTipsBgView];
        [self.view addSubview:self.topTipsLab];
        [self.view addSubview:self.selecttribeTitleLab];
        [self.view addSubview:self.confirmBtn];
        [self.view addSubview:self.tipLab];
    }
}

- (void) setupLayout {
    
    {
        self.reloadBtn.mj_y -= 100;
        self.reloadLab.mj_y -= 100;
    }
    
    {
        [self.topTipsBgView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.mas_equalTo(TJ_NavBarHeight);
            make.left.right.mas_equalTo(0);
            make.height.mas_equalTo(56);
        }];

        [self.topTipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.mas_equalTo(TJ_NavBarHeight);
            make.left.mas_equalTo(30);
            make.right.mas_equalTo(-30);
            make.height.mas_equalTo(56);
        }];
        
        [self.selecttribeTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.mas_equalTo(self.topTipsLab.mas_bottom);
            make.left.mas_equalTo(30);
            make.right.mas_equalTo(-30);
            make.height.mas_equalTo(55);
        }];
        
        [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.height.mas_equalTo(48);
            make.left.mas_equalTo(30);
            make.right.mas_equalTo(-30);
            make.bottom.mas_equalTo(-120);
        }];
        
        [self.tipLab mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.height.mas_equalTo(37);
            make.left.mas_equalTo(30);
            make.right.mas_equalTo(-30);
            make.bottom.mas_equalTo(-20);
        }];
    }
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.selecttribeTitleLab.mas_bottom);
        make.right.left.bottom.mas_equalTo(0);
    }];
}


- (void)initData {
    
    NSNumber *parentId = @0;
    @weakify(self);
    [[[PigMarketApi sharedInstance] areasListWithParentId:parentId] subscribeNext:^(SelectTribesList * _Nullable model) {
        @strongify(self);
    
        [model.list enumerateObjectsUsingBlock:^(SelectTribes * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSMutableArray *citys = [NSMutableArray array];
            [obj.ctiy enumerateObjectsUsingBlock:^(CityItem * _Nonnull cityItem, NSUInteger idx, BOOL * _Nonnull stop) {
                
                CityItem *city = [[CityItem alloc] init];
                NSDictionary *cityDic = (NSDictionary *)cityItem;
                city.ctiyName = [cityDic valueForKey:@"ctiyName"];
                city.ctiyId = [cityDic valueForKey:@"ctiyId"];
                city.isOpen = [cityDic valueForKey:@"isOpen"];
                NSArray *areaList = [cityDic valueForKey:@"area"];
                
                NSMutableArray *areas = [NSMutableArray array];
                [areaList enumerateObjectsUsingBlock:^(id  _Nonnull areaItem, NSUInteger idx, BOOL * _Nonnull stop) {
                    AreaItem *area = [[AreaItem alloc] init];
                    
                    NSDictionary *areaDic = (NSDictionary *)areaItem;
                    area.areaName = [areaDic valueForKey:@"areaName"];
                    area.areaId = [areaDic valueForKey:@"areaId"];
                    area.isOpen = [areaDic valueForKey:@"isOpen"];
                    NSArray *tribalList = [areaDic valueForKey:@"tribe"];

                    NSMutableArray *tribals = [NSMutableArray array];
                    [tribalList enumerateObjectsUsingBlock:^(id  _Nonnull tribalItem, NSUInteger idx, BOOL * _Nonnull stop) {
                        TribeItem *tribal = [[TribeItem alloc] init];
                        NSDictionary *tribalDic = (NSDictionary *)tribalItem;
                        tribal.tribeName = [tribalDic valueForKey:@"tribeName"];
                        tribal.tribeId = [tribalDic valueForKey:@"tribeId"];
                        tribal.isOpen = [tribalDic valueForKey:@"isOpen"];
                        tribal.regionId = [tribalDic valueForKey:@"regionId"];
                        tribal.tribeContact = [tribalDic valueForKey:@"tribeContact"];
                        
                        [tribals addObject:tribal];
                    }];
                    
                    area.tribe = [tribals copy];
                    [areas addObject:area];
                    
                }];
                
                city.area = [areas copy];
                [citys addObject:city];
            }];
            
            obj.ctiy = [citys copy];
        }];

        self.model = model;
        
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
    }];
}


#pragma mark - delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.titles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AdoptTribalSelectedCell *cell = [tableView  dequeueReusableCellWithIdentifier:@"AdoptTribalSelectedCell"];
    
    if (indexPath.row < self.titles.count) {
        cell.titleLab.text = self.titles[indexPath.row];
        cell.detailLab.text = self.values[indexPath.row];
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TribalSelectedBox *box = [[TribalSelectedBox alloc] init];
    
    switch (indexPath.row) {
        case 0:
            {
                box.datas = self.model.list;
                
                self.selectModel.city = -1;
                self.selectModel.country = -1;
                self.selectModel.tribal = -1;
                
                [self.values replaceObjectAtIndex:1 withObject:@""];
                [self.values replaceObjectAtIndex:2 withObject:@""];
                [self.values replaceObjectAtIndex:3 withObject:@""];
                self.selectTribeId = nil;
                
                [self.tableView reloadData];

            }
            break;
            
        case 1:
            {
                if(self.selectModel.province == -1)
                {
                    [self showHudWithMsg:@"请选择省份"];
                    return;
                }
                
                 SelectTribes *item = self.model.list[self.selectModel.province];
                 box.datas = item.ctiy;
                
                self.selectModel.country = -1;
                self.selectModel.tribal = -1;
                
                [self.values replaceObjectAtIndex:2 withObject:@""];
                [self.values replaceObjectAtIndex:3 withObject:@""];
                self.selectTribeId = nil;

                
                [self.tableView reloadData];

                
                }
            break;
        case 2:
            {
                if(self.selectModel.city == -1)
                {
                    [self showHudWithMsg:@"请选择城市"];
                    return;
                }

                SelectTribes *item = self.model.list[self.selectModel.province];
                CityItem *cityItem = item.ctiy[self.selectModel.city];
                box.datas = cityItem.area;
                
                self.selectModel.tribal = -1;
                self.selectTribeId = nil;

                [self.values replaceObjectAtIndex:3 withObject:@""];
                
                [self.tableView reloadData];

            }
            break;
            
        default:
            {
                if(self.selectModel.city == -1)
                {
                    [self showHudWithMsg:@"请选择部落"];
                    return;
                }

                SelectTribes *item = self.model.list[self.selectModel.province];
                CityItem *cityItem = item.ctiy[self.selectModel.city];
                AreaItem *areaItem = cityItem.area[self.selectModel.country];
                box.datas = areaItem.tribe;
            }
            break;
    }
    
    
    
    @weakify(self);
    box.selectBlock = ^(id  _Nonnull item, NSInteger row) {
        @strongify(self);
        
        if ([item isKindOfClass: [SelectTribes class] ]) {
            
            SelectTribes *obj = (SelectTribes *)item;
            self.selectModel.province = row;
            [self.values replaceObjectAtIndex:0 withObject:obj.provinceName];
        }
        
        if ([item isKindOfClass: [CityItem class] ]) {

            CityItem *obj = (CityItem *)item;
            self.selectModel.city = row;
            [self.values replaceObjectAtIndex:1 withObject:obj.ctiyName];
        }

        if ([item isKindOfClass: [AreaItem class] ]) {

            AreaItem *obj = (AreaItem *)item;
            self.selectModel.country = row;
            [self.values replaceObjectAtIndex:2 withObject:obj.areaName];
        }

        if ([item isKindOfClass: [TribeItem class] ]) {

            TribeItem *obj = (TribeItem *)item;
            self.selectModel.tribal = row;
            self.selectTribeId = obj.tribeId;
            [self.values replaceObjectAtIndex:3 withObject:obj.tribeName];
        }
        
        [self.tableView reloadData];
    };
    [box showView];

}

#pragma mark - getter and setter

- (void)registerTableViewCell
{
    self.tableView.separatorColor = KClearColor;
    self.tableView.rowHeight = 61;
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_header.hidden = YES;
    [self.tableView registerClass:[AdoptTribalSelectedCell class] forCellReuseIdentifier:@"AdoptTribalSelectedCell"];
}

- (UIView *)topTipsBgView {
    if (!_topTipsBgView) {
        _topTipsBgView = [[UIView alloc] init];
        _topTipsBgView.backgroundColor = [UIColor colorWithHexString:@"#FFF9D4"];
    }
    return _topTipsBgView;
}


- (YYLabel *)topTipsLab {
    if (!_topTipsLab) {
        _topTipsLab = [[YYLabel alloc] init];
        _topTipsLab.numberOfLines = 0;
        NSString *tipsStr = @"温馨提示：本部落小猪仅可在本部落配送范围内销售，豚集将为您提供屠宰、分割、配送全程冷链物流服务。";
        
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:tipsStr];
        [attributedString yy_setFont:[UIFont smallFont] range:attributedString.yy_rangeOfAll];
        attributedString.yy_lineSpacing = 6;
        attributedString.yy_color = [UIColor colorWithHexString:@"EC8C00"];
        _topTipsLab.attributedText = attributedString;
    }
    return _topTipsLab;
}


- (UILabel *)selecttribeTitleLab {
    if (!_selecttribeTitleLab) {
        _selecttribeTitleLab = [[UILabel alloc] init];
        _selecttribeTitleLab.textColor = [UIColor textBlackColor];
        _selecttribeTitleLab.font = [UIFont middleFont];
        _selecttribeTitleLab.text = @"请您选择一个养猪部落，给小猪落个户口吧！";
    }
    return _selecttribeTitleLab;
}

- (UIButton *)confirmBtn {
    if (!_confirmBtn) {
        _confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_confirmBtn setBackgroundImage:[UIImage imageNamed:@"btn_nomal_bg"] forState:UIControlStateNormal];
        
        @weakify(self);
        _confirmBtn.tapBlock = ^{
            @strongify(self);
            
            if ([JTool iSNull:self.selectTribeId]) {
                [self toastWithContent:@"请选择部落"];
                return;
            }
            //保存部落ID
            UserInfo *userInfo = [UserInfoDataProvider sharedInstance].userInfo;
            userInfo.tribeId = self.selectTribeId;
            [UserInfoDataProvider sharedInstance].userInfo = userInfo;
            
            VarietyListViewController *varietyListVC = [[VarietyListViewController alloc] init];
            //varietyListVC.tribeId = self.selectTribeId;
            varietyListVC.varietiesId = self.varietyId;
            [self.navigationController pushViewController:varietyListVC animated:YES];
        };
        
    }
    return _confirmBtn;
}

- (UILabel *)tipLab{
    
    if (!_tipLab) {
        _tipLab = [UILabel makeLabelWithText:@"当猪出栏时，您可在豚集武清部落所属配送范围内销售。" textColor:UIColorFromRGB(0x999999) font:mFont(12) textAliment:1];
    }
    return _tipLab;
}

- (NSMutableArray *)values{
    
    if (!_values) {
        _values = [NSMutableArray arrayWithArray:@[@"", @"", @"", @""]];
    }
    return _values;
}

- (SelectTribesList *)model{
    
    if (!_model) {
        _model = [[SelectTribesList alloc] init];
    }
    return _model;
}

- (RangeSelectModel *)selectModel{
    
    if (!_selectModel) {
        _selectModel = [[RangeSelectModel alloc] init];
    }
    return _selectModel;
}


- (NSArray *)titles{
    
    if (!_titles) {
        _titles = @[@"选择省份", @"选择城市", @"选择区县", @"选择部落"];
    }
    return _titles;
}

@end

